import React, { useContext, useState, forwardRef, useImperativeHandle } from 'react';
import {
  Form,
  Input,
  Button,
  Checkbox,
  Grid,
  Drawer,
  Notification,
  Select,
} from '@arco-design/web-react';
import locale from './locale';
import useLocale from '@/utils/useLocale';
import { IconSearch } from '@arco-design/web-react/icon';
import styles from './style/index.module.less';
import { IconPlus } from '@arco-design/web-react/icon';
import { post } from '@/utils/request';

const { Row, Col } = Grid;
const { useForm } = Form;
const Option = Select.Option;


const formItemLayout = {
  wrapperCol: {
    span: 24,
  },
};

const SearchForm = forwardRef((props: {
  onSearch: (values: Record<string, any>) => void;
  onSubmit: (value: object) => void;
}, ref) => {
  useImperativeHandle(ref, () => ({
    onAddEdit
  }));

  const t = useLocale(locale);
  const [form] = useForm();
  const [editForm] = useForm();

  const handleSubmit = () => {
    const values = form.getFieldsValue();
    props.onSearch(values);
  };

  const colSpan = 8;
  const [visible,setVisible] = useState(false);
  const [loading,setLoading] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [title,setTitle] = useState('');
  const [options,setOptions] = useState([]);

  const loadRole = () => {
    post('/api/role/list', {
      page: 1,
      size: 500,
    })
    .then((res) => {
      if(res.data){
        setOptions(res.data);
      }
    });
  }

  const onAddEdit = (id:string) => {
    setVisible(true)
    if(options.length==0){
      loadRole();
    }
    let url = ''
    if(id===''){
      url = '/api/user/create'
      setTitle('添加用户')
    }else{
      url = '/api/user/info/' + id
      setTitle('编辑用户')
    }
    setLoading(true);
    post(url, {})
    .then((res) => {
      editForm.setFieldsValue(res.data)
    }).finally(()=>{
      setLoading(false);
    })
  };

  const onOk = () => {
    editForm.validate().then((res) => {
      setConfirmLoading(true);
      post('/api/user/save',editForm.getFieldsValue()).then((res)=>{
        if(res.data){
          setVisible(false);
          props.onSubmit(res.data)
          Notification.info({content: title + '成功。'})
        }
      }).finally(()=>{
        setConfirmLoading(false)
      })
    });
  }

  return (
    <div className={styles['search-form-wrapper']}>
      <Form
        form={form}
        className={styles['search-form']}
        labelAlign="left"
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 19 }}
      >
        <Row gutter={12}>
          <Col span={colSpan}>
            <Form.Item label='用户名' field="keyword">
              <Input placeholder='请输入用户名/姓名' allowClear onPressEnter={handleSubmit} />
            </Form.Item>
            
          </Col>
          <Col span={colSpan}>
            <Button type="primary" icon={<IconSearch />} onClick={handleSubmit}>
            {t['search']}
            </Button>
          </Col>
          <Col span={colSpan} style={{textAlign:'right'}}>
            <Button type="primary" onClick={()=>onAddEdit('')} icon={<IconPlus />}>
              {t['add']}
            </Button>
          </Col>
        </Row>
      </Form>
      <Drawer
        width={600}
        title={title}
        visible={visible}
        confirmLoading={confirmLoading}
        maskClosable={false}
        onOk={onOk}
        onCancel={() => {
          setVisible(false);
        }}
      >
       <Form {...formItemLayout} form={editForm} initialValues={{id:''}} layout='vertical'>
        <Form.Item hidden={true} field='id'><Input /></Form.Item>
        <Form.Item label='用户名' field='username' rules={[{ required: true }]}>
          <Input placeholder='请输入用户名' />
        </Form.Item>
          
        <Form.Item label='姓名' field='name' rules={[{ required: true }]}>
          <Input placeholder='请输入姓名' />
        </Form.Item>

        <Form.Item label='邮箱' field='email'>
          <Input placeholder='请输入邮箱' />
        </Form.Item>

        <Form.Item label='手机号' field='mobile'>
          <Input placeholder='请输入手机号' />
        </Form.Item>
        <Form.Item label='角色' field='roles'>
          <Select
          mode='multiple'
          maxTagCount={5}
          placeholder='请选择角色'
          allowClear
          filterOption={(inputValue, option) =>
            option.props.value.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0 ||
            option.props.children.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
          }
          >
            {options.map((option) => (
              <Option key={option.id} value={option.id}>
                {option.roleName}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item triggerPropName='checked' field='status'>
          <Checkbox>启用</Checkbox>
        </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
});

export default SearchForm;
